import 'dart:async';
import 'dart:developer';
import 'package:logger/logger.dart';
import 'package:sports_new/controller/home/home_logic.dart';
import 'package:sports_new/view/expert/items/league_hot_expert.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:carousel_slider/carousel_controller.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:sports_new/utils/utils.dart';
import '../../base/base_controller.dart';
import '../../entity/expert/expert_hot_entity.dart';
import '../../entity/home/news_item_entity.dart';
import '../../entity/home/news_match_entity.dart';
import '../../entity/other/resource_entity.dart';
import '../../server/api/expert_api.dart';
import '../../server/api/home_api.dart';

class NewsListLogic extends BaseController {
  HomeLogic parent = Get.find<HomeLogic>();
  // ResourceEntity? config;
  String? _id;
  ResourceConfigEntity? config;
  List<ResourceEntity> carousals = [];
  List<ResourceEntity> menus = [];
  List<ResourceEntity> collection = [];
  List<NewsMatchEntity> newsMatches = [];
  List<NewsExpertHotEntity> hotExpert = [];
  List<NewsItemEntity>? newsItems;
  Map<int, bool> existNews = {};
  int _page = 1;
  bool newsEnd = false;
  late Timer timer;
  final carouselController = CarouselSliderController();
  final refreshScroll = ApmScrollController();
  bool autoPlay = true;
  bool visible = false;
  int topNewsCount = 0;
  HotBoardController? boardController;

  String? get id => _id;
  set id(String? value) {
    _id = value;
    update();
  }

  int get page => _page;
  set page(int value) {
    _page = value;
    update();
  }

  void getData() async {
    if (id == null) {
      return;
    }
    await getResources();
    page = 1;
    getNews();
    getNewsMatches();
    getHotExpert();
  }

  getResources() async {
    final l = await HomeApi.getResources(id ?? "");
    var resourceConfig =
        l.filterOrNull((item) => item.button == "config")?.first;
    if (resourceConfig?.content.hasValue == true) {
      config = ResourceConfigEntity.fromContent(resourceConfig!.content);
    }
    carousals = l.filter((item) => item.button == "lbt");
    menus = l.filter((item) => item.button == "menu_item");
    collection = l.filter((item) => item.button == "collection");
    if (config?.sportsId != 0 && config?.leagueId.hasValue == true) {
      boardController = HotBoardController.league(
          sportsId: config!.sportsId!,
          leagueId: config!.leagueId!,
          leagueName: config?.leagueName ?? "");
    }
    update();
  }

  getNewsMatches() async {
    final hotMatch = config?.hotMatch ?? false;
    if (!hotMatch) {
      newsMatches = [];
      update();
      return;
    }
    final l = await HomeApi.getNewsMatchs();
    newsMatches = l;
    update();
  }

  getHotExpert() async {
    bool flag = config?.hotExpert ?? false;
    if (flag) {
      final l = await ExpertApi.getNewsExpertHot();
      if (l != null) {
        hotExpert = l;
        update();
      }
    }
  }

  getNews() async {
    if (config?.infoClassId == null) {
      return;
    }
    final p = page;
    final l = await HomeApi.getNewsList(config!.infoClassId!, page: p);
    if (p != page) {
      return;
    }
    if (p == 1) {
      newsItems = [];
      existNews = {};
    }
    newsEnd = l.isEmpty;
    newsItems?.addAll(l.filter((item) {
      if (existNews[item.id ?? 0] == null) {
        existNews[item.id ?? 0] = true;
        return true;
      }
      return false;
    }));
    topNewsCount =
        (newsItems?.lastIndexWhere((element) => element.top == 1) ?? 0) + 1;
    page += 1;
    update();
  }

  timerFunc() {
    if (!visible) {
      return;
    }
    getNewsMatches();
  }

  @override
  void dispose() {
    timer.cancel();
    refreshScroll.dispose();
    super.dispose();
  }

  @override
  void onInit() {
    refreshScroll.addListener(() {
      log("${refreshScroll.offset}");
      if (refreshScroll.offset < 0 && autoPlay) {
        autoPlay = false;
        carouselController.stopAutoPlay();
      }
      if (refreshScroll.offset >= 0 && !autoPlay) {
        autoPlay = true;
        carouselController.startAutoPlay();
      }
    });
    timer = Timer.periodic(const Duration(seconds: 30), (timer) {
      timerFunc();
    });
    super.onInit();
  }

  @override
  void onReady() {
    getData();
    super.onReady();
  }

  void doRefresh() {
    if (refreshController.headerState?.mode.isIdle == false) return;
    refreshController.callRefresh(scrollController: refreshScroll);
  }

  @override
  Future getRefresh() async => getData();

  @override
  Future loadMore() async {
    await getNews();
    refreshController
        .finishLoad(newsEnd ? IndicatorResult.noMore : IndicatorResult.success);
  }
}
